// 存储键名
const STORAGE_KEYS = {
	RECORDS: 'financial_records',
	BUDGET: 'monthly_budget',
	BACKUP: 'data_backup'
}

// 获取所有记录
export const getRecords = () => {
	const records = uni.getStorageSync(STORAGE_KEYS.RECORDS)
	return records ? JSON.parse(records) : []
}

// 保存所有记录
export const saveRecords = (records) => {
	uni.setStorageSync(STORAGE_KEYS.RECORDS, JSON.stringify(records))
}

// 添加记录
export const addRecord = (record) => {
	const records = getRecords()
	records.unshift(record)
	saveRecords(records)
}

// 更新记录
export const updateRecord = (index, record) => {
	const records = getRecords()
	records[index] = record
	saveRecords(records)
}

// 删除记录
export const deleteRecord = (index) => {
	const records = getRecords()
	records.splice(index, 1)
	saveRecords(records)
}

// 获取月度预算
export const getBudget = () => {
	const budget = uni.getStorageSync(STORAGE_KEYS.BUDGET)
	return budget ? JSON.parse(budget) : null
}

// 保存月度预算
export const saveBudget = (budget) => {
	uni.setStorageSync(STORAGE_KEYS.BUDGET, JSON.stringify(budget))
}

// 备份数据
export const backupData = () => {
	const data = {
		records: getRecords(),
		budget: getBudget()
	}
	uni.setStorageSync(STORAGE_KEYS.BACKUP, JSON.stringify(data))
}

// 恢复数据
export const restoreData = () => {
	const backup = uni.getStorageSync(STORAGE_KEYS.BACKUP)
	if (backup) {
		const data = JSON.parse(backup)
		saveRecords(data.records)
		if (data.budget) {
			saveBudget(data.budget)
		}
		return true
	}
	return false
}

// 导出数据为CSV
export const exportToCSV = () => {
	const records = getRecords()
	const headers = ['类型', '金额', '分类', '日期', '备注']
	const rows = records.map(record => [
		record.type === 'income' ? '收入' : '支出',
		record.amount,
		record.category,
		record.date,
		record.note || ''
	])
	
	const csvContent = [
		headers.join(','),
		...rows.map(row => row.join(','))
	].join('\n')
	
	// 创建并下载文件
	const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
	const url = URL.createObjectURL(blob)
	const link = document.createElement('a')
	link.href = url
	link.download = `财务记录_${new Date().toLocaleDateString()}.csv`
	link.click()
	URL.revokeObjectURL(url)
}

// 获取指定时间范围内的记录
export const getRecordsByDateRange = (startDate, endDate) => {
	const records = getRecords()
	return records.filter(record => {
		const recordDate = new Date(record.date)
		return recordDate >= startDate && recordDate <= endDate
	})
}

// 获取指定月份的记录
export const getRecordsByMonth = (year, month) => {
	const startDate = new Date(year, month - 1, 1)
	const endDate = new Date(year, month, 0)
	return getRecordsByDateRange(startDate, endDate)
}

// 计算收支统计
export const calculateStatistics = (records) => {
	const statistics = {
		totalIncome: 0,
		totalExpense: 0,
		balance: 0,
		categories: {}
	}
	
	records.forEach(record => {
		const amount = Number(record.amount)
		if (record.type === 'income') {
			statistics.totalIncome += amount
		} else {
			statistics.totalExpense += amount
			if (!statistics.categories[record.category]) {
				statistics.categories[record.category] = 0
			}
			statistics.categories[record.category] += amount
		}
	})
	
	statistics.balance = statistics.totalIncome - statistics.totalExpense
	
	// 计算分类占比
	const categoryStats = Object.entries(statistics.categories).map(([name, amount]) => ({
		name,
		amount,
		percentage: (amount / statistics.totalExpense * 100).toFixed(1)
	}))
	
	return {
		...statistics,
		categoryStats
	}
} 